package com.db.drawio.template.db.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Types;

public class DbUtil {

    /**
     * 获取数据库链接对象
     *
     * @param username root
     * @param password 123456
     * @param url      jdbc:mysql://localhost:4040/testdb?useUnicode=true
     * @return connection
     */
    static public Connection getConnection(String username, String password, String url) {
        if (username == null) {
            username = "root";
        }
        if (password == null) {
            password = "123456";
        }
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        // 建立与mysql数据库的链接
        Connection conn;
        try {
            conn = DriverManager.getConnection(url, username, password);
            System.out.println("数据库链接成功");
        } catch (SQLException e) {
            System.out.println("链接数据库错误");
            throw new RuntimeException(e);
        }

        return conn;
    }

    /**
     * 将 SQL 数据类型（java.sql.Types 中的整数常量）转换为可读的字符串
     *
     * @param dataType SQL 数据类型
     * @return 可读的数据类型字符串
     */
    public static String getSqlTypeName(int dataType) {
        switch (dataType) {
            case Types.INTEGER:
                return "INT";
            case Types.BIGINT:
                return "BIGINT";
            case Types.SMALLINT:
                return "SMALLINT";
            case Types.TINYINT:
                return "TINYINT";
            case Types.FLOAT:
                return "FLOAT";
            case Types.DOUBLE:
                return "DOUBLE";
            case Types.DECIMAL:
                return "DECIMAL";
            case Types.NUMERIC:
                return "NUMERIC";
            case Types.CHAR:
                return "CHAR";
            case Types.VARCHAR:
                return "VARCHAR";
            case Types.DATE:
                return "DATE";
            case Types.TIME:
                return "TIME";
            case Types.TIMESTAMP:
                return "TIMESTAMP";
            case Types.BLOB:
                return "BLOB";
            case Types.CLOB:
                return "CLOB";
            case Types.BOOLEAN:
                return "BOOLEAN";
            case Types.BIT:
                return "BIT";
            case Types.BINARY:
                return "BINARY";
            case Types.VARBINARY:
                return "VARBINARY";
            case Types.LONGVARCHAR:
                return "LONGVARCHAR";
            case Types.LONGVARBINARY:
                return "LONGVARBINARY";
            case Types.OTHER:
                return "OTHER";
            default:
                return "UNKNOWN(" + dataType + ")";
        }
    }
}